import {Injectable} from "@angular/core";
import {Http, Headers, Response} from "@angular/http";
import {User} from "./User";
import {LogInPage} from "./log-in";
import {Subject} from "rxjs/Subject";


@Injectable()
export class LoginNewService{

  public rootPage : any;

  public changes: Subject<any> = new Subject<any>();

  public isLoginedFlag : boolean;
  public isMenuDisplayed : boolean;
  public curUser : User;

  public token : string;

  public headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
  // public signupUrl:string="http://localhost:8080/user/register";
  public signupUrl:string="http://127.0.0.1:8080/user/register";
  // public loginUrl : string = "http://localhost:8080/user/login";
  public loginUrl:string="http://127.0.0.1:8080/user/login";
  // public isExisturl : string="http://localhost:8080/user/exist";
  public isExisturl : string="http://127.0.0.1:8080/user/exist";
  // public getcuruserUrl : string = "http://localhost:8080/user/getCurrentUser";
  public getcuruserUrl : string = "http://127.0.0.1:8080/user/getCurrentUser";

  constructor(
    public http: Http,
  ){
    this.isLoginedFlag = false;
    this.isMenuDisplayed = true;

    this.curUser = new User("","");

    this.rootPage = LogInPage;

    this.token = "";
  }
//getCurStudent出现错误
//   getCurStudent(token : String):Promise<User>{
//     let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization': token});
//     return this.http
//       .get(this.getCurStudentUrl, {headers: token_headers})
//       .toPromise()
//       .then(this.extractData)
//       .catch(this.handleError);
//   }
  getCurUser(token : String):Promise<User>{
    let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization': token});
    return this.http
      .get(this.getcuruserUrl, {headers: token_headers})
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }


  changeRoot(root : any){
    this.rootPage = root;
    this.changes.next(this.rootPage);
  }
  signup(user:User): Promise<void> {
    /*this.identification,this.name,this.sex,this.password1,this.school,this.grade,this.strict,this.stuclass*/
    var body = "username=" +user.username+ "&password=" + user.password;
    console.log(body);
    return this.http
      .post(this.signupUrl, body, {headers: this.headers})
      .toPromise()
      .then((response:Response)=>{
      console.log("service.signup");
      console.log(response)});
  }
  login(username : string, password : string): Promise<string> {
    var body = "username=" +username + "&password=" + password;
    return this.http
      .post(this.loginUrl, body, {headers: this.headers})
      .toPromise()
      .then(this.getRes);
  }
  getRes(res:Response){
    let text = res.json();
    console.log(text);
    //this.token = text['content'];
    return text;
  }
  isLogined(isLogined: boolean): void {
    this.isLoginedFlag = isLogined;
    this.changes.next(this.isLoginedFlag);
    this.changes.next(this.curUser);
  }
  changeMenuDisplayed(flag : boolean): void{
    this.isMenuDisplayed = flag;
    this.changes.next(this.isMenuDisplayed);
  }

  public extractData(res: Response) {
    let body = res.json();
    //将拿到的数据进行打印....
    console.log(body);

    return body;
  }
  public userData(res:Response){
    let body=res.json();
    console.log(body);
    console.log(res);

    return body;
  }
  private handleError (error: Response | any) {
    console.log("有错误???");
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Promise.reject(errMsg);
  }
   isExist(username : string) : Promise <string> {

     let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});

     return this.http.get(this.isExisturl+"?username="+username,{headers: token_headers}).toPromise()
       .then(this.userData)
       .catch(this.handleError);
   }

}
